package com.news.reader;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.net.nntp.Article;
import org.apache.commons.net.nntp.NNTPClient;
import org.apache.commons.net.nntp.NewsgroupInfo;

public final class NewsgroupsInfo {
	private NewsgroupInfo[] list;
	private NNTPClient client;
    
	public NewsgroupsInfo(String NNTPServer, int NNTPPort) {
	    client = new NNTPClient();
		try {
			client.connect(NNTPServer, NNTPPort);
			list = client.listNewsgroups();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
/*		} finally {
            try {
                if (client.isConnected())
                    client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
*/
        }
	}
    
	public List<String> getGroupNameList() {
	    List<String> items = new ArrayList<String>();
        if (list != null){
            for (int i = 0; i < list.length; i++){
                items.add(list[i].getNewsgroup());
            }
        } 
        Collections.sort(items);
		return items;
	}
	
	public List<String> getThreadSubjects(String newsgroup) {
		List<String> Subjects = new ArrayList<String>(); 
		NewsgroupInfo group = new NewsgroupInfo();
		try {
			client.selectNewsgroup("newsgroup.hkland.tsimshatsui", group);
			int highArticleNumber = group.getLastArticle();
			int lowArticleNumber = highArticleNumber - 100;
			Article[] articles = NNTPUtils.getArticleInfo(client, lowArticleNumber, highArticleNumber);
			for (int i = 0; i < articles.length; i++) {
			 	Subjects.add(NNTPUtils.getASCIIToBig5String(articles[i].getSubject()));
				//Subjects.add(NNTPUtils.getASCIIToBig5String(articles[i].simplifiedSubject()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Subjects;
	}
	
	public void doDestroy() {
        try {
            if (client.isConnected())
                client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}
